package com.yootk.listener;

import jakarta.servlet.ServletContext;
import jakarta.servlet.ServletContextEvent;
import jakarta.servlet.ServletContextListener;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebListener;

import java.util.EventListener;

/**
 * 动态注册Listener组件
 */
@WebListener
public class DynamicRegistrationListener implements ServletContextListener {

    @Override
    public void contextInitialized(ServletContextEvent sce) { // 容器初始化进行组件注册
        // 所有的组件的动态注册都是基于ServletContext接口实例完成的
        ServletContext application = sce.getServletContext(); // 获取上下文接口实例
        try {
            EventListener listener = application.createListener(SessionStateMonitor.class); // 创建一个事件监听类
            application.addListener(listener);
            // 等价操作：application.addListener("com.yootk.listener.UserStateMonitor");
        } catch (ServletException e) {
            e.printStackTrace();
        }
    }
}
